
package LogCount;

use strict vars;

use vars qw(%months @lastday);

# translation of monthnames (correct ones)
%months = (
"Jan" => 1,
"Feb" => 2,
"Mar" => 3,
"Apr" => 4,
"May" => 5,
"Jun" => 6,
"Jul" => 7,
"Aug" => 8,
"Sep" => 9,
"Oct" => 10,
"Nov" => 11,
"Dec" => 12,
	   );
# Last day of months
# Note missing leapday correction....
@lastday = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

sub apachetosimple {
    my $str = shift;
    my $byhour = shift;
    my ($month, $year, $day, $zone, $hour);
    if ($str =~ /^(\d+)\/(\S\S\S)\/(\d+):(\d+):\d+:\d+ \+(\d+)00/) {
                  #1 day  #2 mn    #3 y  #4 h           #5 zone
	$month = $months{$2};
        $year = $3;
        $day = $1;
        $zone = $5;
	if ($byhour) {
	    $hour = $4;
            # Adjust for zone
            $hour -= $5;
            if ($hour < 0) {
               $hour += 24;
               $day--;
               if ($day == 0) {
                  $month--;
                  if ($month == 0) {
                     $year--;
                     $month = 12;
                  }
                  $day = $lastday[$month];
               }
            }
	} else {
	    $hour = 0;
	}
	my $date = sprintf "%4d-%02d-%02dT%02d", $year, $month, $day, $hour;
	return $date;
    } else {
	warn "apachetosimple: Improper date: $str\n";
	return "0000-00-00T00";
    }
    
}

sub zerofilltimes {
# Patch in some zeroes for missing dates/hours
    my ($count, $byhour) = @_;
    my @keys = sort(keys(%$count));
    my $firstkey = $keys[0];
    my $lastkey = $keys[$#keys];
    my ($day, $month, $hour, $nexthour, $nextday, %donefill);
    for $day (keys(%$count)) {
	if ($day =~ /(\d+-\d+-)(\d+)T(\d+)/) {
	    $month = $1;
	    $hour = $3;
	    next if $donefill{$month};
	    for $day (1..28) {
		$nextday = $month . sprintf("%02d", $day);
		next if $nextday lt $firstkey;
		last if ($nextday . "T23") gt $lastkey;
		if ($byhour) {
		    for $hour (0..23) {
			$nexthour = $nextday . sprintf("T%02d", $hour);
			last if ($nexthour gt $lastkey);
			$$count{$nexthour} = 0 if !defined($$count{$nexthour});
		    }
		} else {
		    $nextday .= "T00";
		    $$count{$nextday} = 0 if !defined($$count{$nextday});
		}
	    }
	    $donefill{$month} = 1;
	}
    }
}

1;
